package com.atguigu.chapter11;

import com.atguigu.chapter05.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.types.Row;

import java.time.Duration;

import static org.apache.flink.table.api.Expressions.$;

/**
 * TODO
 *
 * @author cjp
 * @version 1.0
 * @date 2021/3/12 9:30
 */
public class Flink02_TableAPI_GroupBy {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        SingleOutputStreamOperator<WaterSensor> sensorDS = env
                .socketTextStream("localhost", 9999)
                .map(new MapFunction<String, WaterSensor>() {
                    @Override
                    public WaterSensor map(String value) throws Exception {
                        // 切分
                        String[] line = value.split(",");
                        return new WaterSensor(line[0], Long.valueOf(line[1]), Integer.valueOf(line[2]));

                    }
                })
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner((value, ts) -> value.getTs() * 1000L)
                );


        // TODO - TableAPI 基本写法
        // 1、创建表的执行环境
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        // 2、将 流 转换成 Table对象
        Table sensorTable = tableEnv.fromDataStream(sensorDS);

        // 3、使用 TableAPI对 动态表 进行操作
        Table resultTable = sensorTable
                .groupBy($("id"))
//                .aggregate($("id").count().as("cnt"))
//                .select($("id"),$("cnt"));
                .select($("id"),$("id").count().as("cnt"));

        // 4、将 动态表 转换成 流
        DataStream<Tuple2<Boolean, Row>> resultDS = tableEnv.toRetractStream(resultTable, Row.class);


        resultDS.print();

        env.execute();
    }
}
/*
    撤回流 -> 历史数据更新：
        1）先把 原先的结果 标记为 撤回，也就是 false
        2）把 新的结果 标记为 插入，也就是 true

    Upsert流： 插入或更新
        如果不存在，直接插入
        如果存在，直接更新

        判断的依据，唯一主键，依赖于外部系统，比如：ES
 */